﻿using System.Data;
using System.Web.Script.Services;
using System.Web.Services;
using EnumKeys;
using Webapp;
namespace xundh.API.WF
{
    /// <summary>
    ///WF_Items 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://www.lansezhongjie.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.Web.Script.Services.ScriptService]

    public class WF_Items : BaseService
    {
        /// <summary>
        /// 启动一个工作流，代码调用时，Form要定义在Template里
        /// </summary>
        /// <param name="ItemId"></param>
        /// <param name="TemplateTitle"></param>
        /// <param name="FilePath"></param>
        /// <param name="Id">扩展模块 记录的id</param>
        /// <param name="identifyKey">扩展模块 表的key字段名称</param>
        /// <returns></returns>
        //[WebMethod(EnableSession = true, Description = "启动一个工作流")]
        public EnumKeys.ServiceStateKeys AddTemplateTitle(int ItemId, string TemplateTitle, string FilePath, int Id, string identifyKey)
        {
            WF_Templates serviceWFTemplates = new WF_Templates();
            xundh.Model.WF_Templates m = serviceWFTemplates.QueryTitle(TemplateTitle);
            string Params = "";
            foreach (string key in REQUEST.QueryString.AllKeys)
            {
                if (key == identifyKey)
                    Params += "&" + identifyKey + "=" + Id;
                else
                    Params += "&" + key + "=" + REQUEST[key].ToString();
            }
            foreach (string key in REQUEST.Form.AllKeys)
            {
                if (key == identifyKey)
                    Params += "&" + identifyKey + "=" + Id;
                else
                    Params += "&" + key + "=" + REQUEST[key].ToString();
            }
            Params = Params.Trim('&');
            return Add(ItemId, m.TemplateId, m.Form, Params, FilePath);
        }

        [WebMethod(EnableSession = true, Description = "启动一个工作流")]
        public ServiceStateKeys Add(int ItemId, int TemplateId, string Form, string Params, string FilePath)
        {
            ///Session
            if (U == null) return ServiceStateKeys.TimeOut;
            ///参数处理

            xundh.BLL.WF_Items bll = new xundh.BLL.WF_Items();
            xundh.Model.WF_Items m;
            if (ItemId > 0)
                m = bll.GetModel(ItemId);
            else
            {
                m = new xundh.Model.WF_Items();

                m.AddTime = NOW;
                m.AddUserId = U.UserId;
                m.AddUser = U.UserName;
                m.AddIp = IP;
                m.AddDepartId = U.DepartId;
                m.TemplateId = TemplateId;
                m.State = (int)WFState.Need;
            }
            m.Form = Form;
            m.Params = Params;
            m.LastTime = NOW;
            m.LastUserId = U.UserId;
            m.LastUser = U.UserName;
            m.LastIp = IP;
            if (FilePath != "")
                m.FilePath = FilePath;
            if (ItemId > 0)
                bll.Update(m);
            else
            {
                m.ItemId = bll.Add(m);
                //启动流程
                NodeOperate nodeOperate = new NodeOperate(m.ItemId);
                ServiceStateKeys result = nodeOperate.Start();
                if (result == ServiceStateKeys.HardErr)
                {
                    //回滚
                    bll.Delete(m.ItemId);
                    return ServiceStateKeys.HardErr;
                }

                m.NowNodeName = nodeOperate.ModelWFItems.NowNodeName;
                m.NowToUserIds = nodeOperate.ModelWFItems.NowToUserIds;
                m.NowToUsers = nodeOperate.ModelWFItems.NowToUsers;
                m.NowWorkFlowId = nodeOperate.ModelWFItems.NowWorkFlowId;
                m.SpecifyIds = nodeOperate.ModelWFItems.SpecifyIds;
                m.SpecifyNames = nodeOperate.ModelWFItems.SpecifyNames;

                bll.Update(m);
            }
            return ServiceStateKeys.Success;
        }

        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public JsonTable GetLists(int page, int rows, string action)
        {
            if (U == null) return null;
            xundh.BLL.BasePager bll = new BLL.BasePager();
            string where = " 1=1 ";
            string table = "v_WF_Items_Templates_Types";
            switch (action)
            {
                case "MyPost":
                    where += " AND AddUserId= " + U.UserId;
                    break;
                case "ToMy":
                    where += " AND ','+NowUsersIds +',' LIKE '%," + U.UserId + ",%'";
                    break;
                case "NeedMy":
                    //权限
                    where += " AND ',' + SpecifyIds + ',' LIKE '%," + U.UserId + ",%' AND State=" + (int)WFState.Need;
                    break;
                default:
                    //权限
                    RBAC.RBAC_Users serviceRBACUsers = new RBAC.RBAC_Users();
                    if (serviceRBACUsers.CheckResouceOperationLimit(U.UserId, "流程管理", "查所有"))
                    {

                    }
                    else if (serviceRBACUsers.CheckResouceOperationLimit(U.UserId, "流程管理", "查部门"))
                    {
                        where += " AND AddDepartId=" + U.DepartId;
                    }
                    else
                        where += " AND ',' + SpecifyIds + ',' LIKE '%," + U.UserId + ",%'";
                    break;
            }
            JqGridHandler datagrid = new JqGridHandler(where);
            int recordcount = bll.GetAllCount(datagrid.StrWhere, table);

            string cols = "ItemId,AddTime,AddUserId,AddUser,Title,Name,State,TemplateId,LastTime,LastUser,NowToUsers,AddDepartId";//Title:Template Name:WF_Type
            datagrid.init(datagrid.StrWhere, page, recordcount, rows, "", "");
            if (datagrid.Order == "") datagrid.Order = "ItemId DESC";
            using (DataSet ds = bll.GetPager(datagrid.Pagesize, datagrid.P, datagrid.StrWhere, datagrid.Order, table, cols))
            {
                return new JsonTable(ds.Tables[0], recordcount, datagrid.P, datagrid.Recordcount);
            }
        }
        [WebMethod(EnableSession = true)]
        [ScriptMethod(UseHttpGet = true)]
        public xundh.Model.WF_Items Query(int id)
        {
            if (U == null) return null;
            xundh.BLL.WF_Items bll = new xundh.BLL.WF_Items();
            xundh.Model.WF_Items m = bll.GetModel(id);

            return m;
        }

        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Delete(int id)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.BLL.WF_Items bll = new xundh.BLL.WF_Items();
            bll.Delete(id);
            return ServiceStateKeys.Success;
        }
        /// <summary>
        /// Pass, Need, Stop, NotPass
        /// </summary>
        /// <param name="ItemId"></param>
        /// <param name="WorkFlowId"></param>
        /// <param name="Suggest"></param>
        /// <param name="State">0通过 1待批 2终止 4未通过</param>
        /// <returns></returns>
        [WebMethod(EnableSession = true)]
        public ServiceStateKeys Verify(int ItemId, string Suggest, int State)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            ////生成下一步骤
            NodeOperate nodeOperate = new NodeOperate(ItemId);
            if (State == (int)WFState.Finish) { }
            else if (State == (int)WFState.NotPass)
            {
                //驳回的流程。
            }
            ServiceStateKeys result = nodeOperate.Verify(Suggest, State);
            //流程结束
            xundh.BLL.WF_Items bll = new BLL.WF_Items();
            xundh.Model.WF_Items m = bll.GetModel(ItemId);
            m.LastIp = IP;
            m.LastTime = NOW;
            m.LastUser = U.UserName;
            m.LastUserId = U.UserId;
            if (result == ServiceStateKeys.NotInUse)
            {
                m.NowNodeName = "结束";
                m.NowToUserIds = "";
                m.NowToUsers = "";
                m.NowWorkFlowId = 0;
                m.State = (int)WFState.Finish;
            }
            else if (result == ServiceStateKeys.Success)
            {
                //找到新的workflowid
                m.NowNodeName = nodeOperate.ModelWFItems.NowNodeName;
                m.NowToUserIds = nodeOperate.ModelWFItems.NowToUserIds;
                m.NowToUsers = nodeOperate.ModelWFItems.NowToUsers;
                m.NowWorkFlowId = nodeOperate.ModelWFItems.NowWorkFlowId;
                m.SpecifyIds = nodeOperate.ModelWFItems.SpecifyIds;
                m.SpecifyNames = nodeOperate.ModelWFItems.SpecifyNames;
                m.State = (int)WFState.Need;
            }
            bll.Update(m);

            return ServiceStateKeys.Success;
        }
        [WebMethod(EnableSession = true, Description = "更改流程状态")]
        public ServiceStateKeys ChangeState(int id, int State)
        {
            if (U == null) return ServiceStateKeys.TimeOut;
            xundh.BLL.WF_Items bll = new xundh.BLL.WF_Items();
            xundh.Model.WF_Items m = bll.GetModel(id);
            m.State = State;
            m.LastIp = IP;
            m.LastTime = NOW;
            m.LastUser = U.UserName;
            m.LastUserId = U.UserId;
            bll.Update(m);
            return ServiceStateKeys.Success;
        }
    }
}
public enum WFState { Need, Finish, Stop, Delete, NotPass }
//public enum WFNodeState { Pass, Need, Stop, NotPass }